package com.logicwin.aibala.detailPackActivity;

import java.util.List;

import com.logicwin.aibala.Aibala;
import com.logicwin.aibala.R;
import com.logicwin.aibala.action.DownloadSoftwareAction;
import com.logicwin.aibala.action.LoadDetailAction;
import com.logicwin.aibala.action.LoadDetailListener;
import com.logicwin.aibala.model.androidSWInfo.APKListItem;
import com.logicwin.aibala.model.androidSWInfo.APKTotalInfo;
import com.logicwin.aibala.services.file.AsyncImage;
import com.logicwin.aibala.services.file.ImageManager;
import com.logicwin.aibala.ui.screens.screenmain.ScreenHome;
import com.logicwin.aibala.utils.MyLog;
import com.logicwin.aibala.utils.StringUtils;
import com.logicwin.aibala.utils.UnitTran;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AbsListView.OnScrollListener;


public class DetailDesc extends Activity implements OnTouchListener, OnGestureListener{
	
	private final static String tag = "DetailDesc";
	private static Context mContext;
	
	public static Handler messageHandler;
	
	private Button mIntroduceButton;
	private Button mCommentButton;
	private Button mReferenceButton;
	private Button mWhouseButton;
	
	private ViewFlipper mViewFlipper;
	private ScrollView mScrollView;
	
	private LinearLayout mMenuLayout;
	
	private int mCurrentButtonPressed;
	
	private GestureDetector mGestureDetector;
	
	private APKTotalInfo mAPKTotalInfo = null;
	
	private ProgressBar mDownloadingProgress;
	private ImageButton mDownloadingCancel;
	
	private DownloadSoftwareAction downloadAction = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Aibala.setCurrentContext(this);
		mContext = this;
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.package_detail);
		Looper looper = Looper.myLooper();
        messageHandler = new MessageHandler(looper);
        
        mDownloadingProgress = (ProgressBar)findViewById(R.id.detail_download_progress);
        mDownloadingCancel = (ImageButton)findViewById(R.id.detail_download_cancel);
        mDownloadingProgress.setVisibility(View.GONE);
        mDownloadingCancel.setVisibility(View.GONE);
		
		Button btnRet = (Button) this.findViewById(R.id.detail_btn_ret);
		btnRet.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				Aibala.setCurrentContext(ScreenHome.mContext);
			}			
		});
		
		Intent intent = this.getIntent();
//		mAPKItem = (APKListItem)intent.getSerializableExtra("apkItem");
		
		final int apkId = intent.getIntExtra("apkId", 0);
		downloadAction = DownloadSoftwareAction.getInstance(apkId);
		
		new LoadDetailAction().startLoad(apkId, new LoadDetailListener(){

			@Override
			public void loadDetailTextDone() {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void loadDetailPictureDone(int index) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void loadDone(APKTotalInfo apkTotalInfo) {
				// TODO Auto-generated method stub
				if (apkTotalInfo!=null){
					mAPKTotalInfo = apkTotalInfo;
					
					mAPKTotalInfo.getBasicInfo().setID(apkId);
				}
				Message message = Message.obtain();
                message.obj = "loadDone";
                messageHandler.sendMessage(message);
//				initAPKInfo();
//				initButtons();
//				initViewFlipper();
			}
		});
	}
	
	private void inflateLevel(int level){
		int mHighestLevel = 5;
		int mLowestLevel  = 0;
		if(level <mLowestLevel || level >mHighestLevel) {
			MyLog.warn(tag+"-inflateLevel", "mLevel is out of range, mLevel value is "+ level);
		}
		if(level<mLowestLevel) level = mLowestLevel;
		if(level>mHighestLevel) level = mHighestLevel;
		ImageView imagestars[] = new ImageView[mHighestLevel];
		imagestars[0]  = (ImageView) findViewById(R.id.detail_star_image1);
		imagestars[1]  = (ImageView) findViewById(R.id.detail_star_image2);
		imagestars[2]  = (ImageView) findViewById(R.id.detail_star_image3);
		imagestars[3]  = (ImageView) findViewById(R.id.detail_star_image4);
		imagestars[4]  = (ImageView) findViewById(R.id.detail_star_image5);
		int idex = 0;
		for(; idex <level; idex++){
			imagestars[idex].setImageDrawable(this.getResources().getDrawable(R.drawable.star_true));
		}
		for(;idex < mHighestLevel; idex++){
			imagestars[idex].setImageDrawable(this.getResources().getDrawable(R.drawable.star_false));
		}		
	}
	
	private void initAPKInfo(){
		if (mAPKTotalInfo==null)
			return;
		ImageButton downCancelButton = (ImageButton) this.findViewById(R.id.detail_download_cancel);
		downCancelButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				downloadAction.stop();
			}			
		});
		
		inflateLevel(mAPKTotalInfo.getBasicInfo().getRefStarCount());
		ImageButton downButton = (ImageButton) this.findViewById(R.id.detail_download);
		downButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				downloadAction.startAction(mAPKTotalInfo.getBasicInfo().getAPKAddress(), mAPKTotalInfo.getBasicInfo().getID());
			}			
		});
		
		ProgressBar progressBar = (ProgressBar)findViewById(R.id.detail_progress);
		progressBar.setVisibility(ProgressBar.GONE);
		TextView detail_title = (TextView) this.findViewById(R.id.detail_title);
		
		detail_title.setText(mAPKTotalInfo.getBasicInfo().getAPKName());
		
		final ImageView detail_package_image = (ImageView) this.findViewById(R.id.detail_package_image);
//		detail_package_image.setImageResource(mAPKItem.getIconResID());
		
		Bitmap cacheImage = AsyncImage.asyncLoadIconImage(mAPKTotalInfo
				.getBasicInfo().getIconURL(), new AsyncImage.ImageCallback() {
			// 请参见实现：如果第一次加载url时下面方法会执行
			public void imageLoaded(Bitmap image) {
				detail_package_image.setImageBitmap(image);
			}
		});
		if (cacheImage != null) {
			detail_package_image.setImageBitmap(cacheImage);
		}
		else {
			detail_package_image.setImageResource(R.drawable.image);
		}
		
//		detail_package_image.setImageBitmap(mAPKTotalInfo.getBasicInfo().getIcon());
		
		TextView detail_package_name = (TextView)this.findViewById(R.id.detail_package_name);
		detail_package_name.setText(mAPKTotalInfo.getBasicInfo().getAPKName());
		TextView detail_package_size = (TextView)this.findViewById(R.id.detail_package_size);
		detail_package_size.setText(mAPKTotalInfo.getBasicInfo().getAPKSize());
		TextView detail_package_times = (TextView)this.findViewById(R.id.detail_package_times);
		detail_package_times.setText(mAPKTotalInfo.getBasicInfo().getDownloadCount());
		
		mScrollView = (ScrollView) this.findViewById(R.id.detail_scroll);
		mMenuLayout = (LinearLayout)this.findViewById(R.id.detail_menu);
	}
	
	private void setButtonStatus(int index, boolean isPressed){
		switch(index)
		{
		case BUTTON_INTRODUCE:
			if(isPressed) 	{mIntroduceButton.setBackgroundColor(0x9fd100); 
			mMenuLayout.setBackgroundResource(R.drawable.nav_description);}
			else	      	mIntroduceButton.setBackgroundColor(0);	
			break;
			
		case BUTTON_COMMENT:
			if(isPressed) 	{mIntroduceButton.setBackgroundColor(0x9fd100);
			mMenuLayout.setBackgroundResource(R.drawable.nav_comment);}
			else	      	mIntroduceButton.setBackgroundColor(0);	
			break;
			
		case BUTTON_REFERENCE:
			if(isPressed) 	{mIntroduceButton.setBackgroundColor(0x9fd100);
			mMenuLayout.setBackgroundResource(R.drawable.nav_recommend);}
			else	      	mIntroduceButton.setBackgroundColor(0);	
			break;
			
		case BUTTON_WHOUSE:
			if(isPressed) 	{mIntroduceButton.setBackgroundColor(0x9fd100);
			mMenuLayout.setBackgroundResource(R.drawable.nav_users);}
			else	      	mIntroduceButton.setBackgroundColor(0);	
			break;
		default:
			break;
		}
		
	}
	
	private void initButtons(){
		mIntroduceButton = (Button) this.findViewById(R.id.detail_menu_introduce);
		mCommentButton = (Button) this.findViewById(R.id.detail_menu_comment);
		mReferenceButton = (Button) this.findViewById(R.id.detail_menu_reference);
		mWhouseButton = (Button) this.findViewById(R.id.detail_menu_whouse);
		
		mIntroduceButton.setOnClickListener(new ButtonClickListener(BUTTON_INTRODUCE));
		mCommentButton.setOnClickListener(new ButtonClickListener(BUTTON_COMMENT));
		mReferenceButton.setOnClickListener(new ButtonClickListener(BUTTON_REFERENCE));
		mWhouseButton.setOnClickListener(new ButtonClickListener(BUTTON_WHOUSE));
		
		mCurrentButtonPressed = BUTTON_INTRODUCE;
		setButtonStatus(BUTTON_INTRODUCE,true);
	}
	
	private void initViewFlipper(){
		mGestureDetector = new GestureDetector(this);

		mViewFlipper = (ViewFlipper)this.findViewById(R.id.detail_flipper);
		ListView detail_introduce_control = (ListView) findViewById(R.id.detail_introduce_control);
		detail_introduce_control.setOnScrollListener(new FlipperScrollListener(BUTTON_INTRODUCE));
		detail_introduce_control.setOnTouchListener(this);
		
		ListView detail_comment_control = (ListView) findViewById(R.id.detail_comment_control);
		detail_comment_control.setOnScrollListener(new FlipperScrollListener(BUTTON_INTRODUCE));
		detail_comment_control.setOnTouchListener(this);
		
		ListView detail_reference_control = (ListView) findViewById(R.id.detail_reference_control);
		detail_reference_control.setOnScrollListener(new FlipperScrollListener(BUTTON_INTRODUCE));
		detail_reference_control.setOnTouchListener(this);
		
		ListView detail_whouse_control = (ListView) findViewById(R.id.detail_whouse_control);
		detail_whouse_control.setOnScrollListener(new FlipperScrollListener(BUTTON_INTRODUCE));
		detail_whouse_control.setOnTouchListener(this);
		
		initFlipperIntroduce();
	}
	
	private void initFlipperIntroduce(){
		TextView detail_introduce_text = (TextView) findViewById(R.id.detail_introduce_text);
		detail_introduce_text.setText(mAPKTotalInfo.getDetailDesc().getDescription());
		LinearLayout detail_introduce_images = (LinearLayout) findViewById(R.id.detail_introduce_images);
		
		List<String> sampleImages = mAPKTotalInfo.getDetailDesc().getSamplePic();
		TextView blankView = new TextView(this);
		blankView.setLayoutParams(new LinearLayout.LayoutParams(UnitTran.dip2px(this, 20), UnitTran.dip2px(this, 300)));
		detail_introduce_images.addView(blankView);
		for (int i=0;i<sampleImages.size();i++){
			ImageView imageView = new ImageView(this);
			imageView.setLayoutParams(new LinearLayout.LayoutParams(UnitTran.dip2px(this, 240), UnitTran.dip2px(this, 300)));
			final ImageView finalImage = imageView;
			
			Bitmap cacheImage = AsyncImage.asyncLoadDetailImage(sampleImages.get(i), new AsyncImage.ImageCallback() {
				// 请参见实现：如果第一次加载url时下面方法会执行
				public void imageLoaded(Bitmap image) {
					finalImage.setImageBitmap(image);
				}
			});
			if (cacheImage != null) {
				imageView.setImageBitmap(cacheImage);
			}
			else {
				imageView.setImageResource(R.drawable.image);
			}
			
//			BitmapDrawable bd=new BitmapDrawable(ImageManager.getImage(sampleImages.get(i)));
//			
//			imageView.setBackgroundDrawable(bd);
			detail_introduce_images.addView(imageView);
			
			TextView tempView = new TextView(this);
			tempView.setLayoutParams(new LinearLayout.LayoutParams(UnitTran.dip2px(this, 20), UnitTran.dip2px(this, 300)));
			detail_introduce_images.addView(tempView);
		}
		
		TextView detail_introduce_other = (TextView) findViewById(R.id.detail_introduce_other);
		detail_introduce_other.setText(mAPKTotalInfo.getDetailDesc().getProducer()+"\n"+
				mAPKTotalInfo.getDetailDesc().getShareGuy()+"\n"+
				mAPKTotalInfo.getDetailDesc().getPlatform()+"\n"+
				mAPKTotalInfo.getBasicInfo().getVersion());
	}
	
	private void showPrevFlipper(){
		setButtonStatus(mCurrentButtonPressed,false);
		mCurrentButtonPressed --;
		setButtonStatus(mCurrentButtonPressed,true);	
		mViewFlipper.showPrevious();
		mScrollView.scrollTo(0, 0);
	}
	
	private void showNextFlipper(){	
		setButtonStatus(mCurrentButtonPressed,false);
		mCurrentButtonPressed ++;
		setButtonStatus(mCurrentButtonPressed,true);	
		mViewFlipper.showNext();
		mScrollView.scrollTo(0, 0);
	}

	@Override
	public boolean onDown(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		final int FLING_MIN_DISTANCE = 100, FLING_MIN_VELOCITY = 150;  
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
	        mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(getApplicationContext(), 
	        		R.anim.push_left_in));
	        mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(getApplicationContext(), 
	        		R.anim.push_left_out));	
	       
	        if (mViewFlipper.getCurrentView().getId() != R.id.detail_whouse)
	        	showNextFlipper();	      

		} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
	        mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(getApplicationContext(), 
	        		R.anim.push_right_in));
	        mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(getApplicationContext(), 
	        		R.anim.push_right_out)); 			

	        if(mViewFlipper.getCurrentView().getId() != R.id.detail_introduce)
	        	showPrevFlipper();
		}		
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return mGestureDetector.onTouchEvent(event); 
	}
	
	private final int BUTTON_INTRODUCE 			= 0;
	private final int BUTTON_COMMENT		 	= 1;
	private final int BUTTON_REFERENCE 			= 2;
	private final int BUTTON_WHOUSE 			= 3;
	
	class  ButtonClickListener implements OnClickListener{
		
		public ButtonClickListener(int index){mButtonType = index;}
		
		public void onClick(View v) {
			setButtonStatus(mCurrentButtonPressed,false);
			mCurrentButtonPressed = mButtonType;
			setButtonStatus(mCurrentButtonPressed,true);
			mViewFlipper.setDisplayedChild(mCurrentButtonPressed);
		}		
		private int mButtonType;
	};	
	
	class FlipperScrollListener implements OnScrollListener{

		private final int mnInterval = 3;
		private int mType;
		public FlipperScrollListener(int type){
			mType = type;			
		}
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			if(firstVisibleItem + visibleItemCount < totalItemCount - mnInterval)
				return;
		}

	}
	
	class MessageHandler extends Handler {

        public MessageHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
        	String msgStr = (String)msg.obj;
        	
        	if (msgStr.equals("loadDone")){
	        	initAPKInfo();
				initButtons();
				initViewFlipper();
        	}
        	else if (msgStr.startsWith("startDownload")){
        		MyLog.info(tag, "handleMessage  "+msgStr);
        		String[] temp = msgStr.split("/");
        		if (mAPKTotalInfo!=null){
        		if (temp[1].equals(""+mAPKTotalInfo.getBasicInfo().getID())){
	        		mDownloadingProgress.setVisibility(View.VISIBLE);
	        		mDownloadingCancel.setVisibility(View.VISIBLE);
        		}
        		else {
        			mDownloadingProgress.setVisibility(View.GONE);
            		mDownloadingCancel.setVisibility(View.GONE);
        		}
        		}
        	}
        	else if (msgStr.startsWith("endDownload")){
        		MyLog.info(tag, "handleMessage  "+msgStr);
        		String[] temp = msgStr.split("/");
        		if (mAPKTotalInfo!=null){
        		if (temp[1].equals(""+mAPKTotalInfo.getBasicInfo().getID())){
	        		mDownloadingProgress.setVisibility(View.GONE);
	        		mDownloadingCancel.setVisibility(View.GONE);
        		}
        		}
        	}
        	else if (msgStr.startsWith("downloading")){
        		MyLog.info(tag, "handleMessage  "+msgStr);
        		
        		String[] temp = msgStr.split("/");
        		if (mAPKTotalInfo!=null){
        		if (temp[2].equals(""+mAPKTotalInfo.getBasicInfo().getID())){
	        		mDownloadingProgress.setVisibility(View.VISIBLE);
	        		mDownloadingCancel.setVisibility(View.VISIBLE);
	        		mDownloadingProgress.setProgress(Integer.parseInt(temp[1]));
        		}
        		}
        		//mDownloadingProgress.setSecondaryProgress(Integer.parseInt(temp[1]));
        	}
        	else if (msgStr.startsWith("cancelDownload")){
        		MyLog.info(tag, "handleMessage  "+msgStr);
        		String[] temp = msgStr.split("/");
        		if (mAPKTotalInfo!=null){
        		if (temp[1].equals(""+mAPKTotalInfo.getBasicInfo().getID())){
	        		mDownloadingProgress.setVisibility(View.GONE);
	        		mDownloadingCancel.setVisibility(View.GONE);
        		}
        		}
        	}
        }

    }
}
